<?php

namespace App\Service\Message;

use App\Cache\UserRemarkCache;
use App\Model\CallBase;
use App\Model\CallComment;
use App\Model\User;
use App\Model\UserProfile;
use App\Service\BaseService;

/**
 * 通话记录
 */
class VoiceCallListService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $this->userId = $userId;
        $appId = $this->request->input('appid', 1);
        $version = $this->request->input('version', '');
        $page = $this->request->input('page', 1);
        $chatUserIds = $this->request->input('chat_userids', '');
        //个人资料
        // $myProfile = UserProfile::getProfile($userId);
        // if ($myProfile->gender == 1) return ['list' => []];
        //语聊记录
        $list = CallBase::getUserLogs($userId, $page, $this->pageNum);
        $chatUserIds = array_column($list, 'chat_user_id');
        //批量获取用户资料
        $users = UserProfile::getUsersProfile($chatUserIds);
        // check_dev_env() && log_info("==" . json_encode($list));
        $profiles = [];
        foreach ($users as $user) $profiles[$user['user_id']] = $user;
        $ret = ['list' => []];
        foreach ($list as $item) {
            $profile = $profiles[$item['chat_user_id']] ?? [];
            $log = CallBase::buildItem($item, $profile);
            if (!$log) continue;
            //是否可以语聊
            $log['can_call'] = UserProfile::checkCanCall($profile['role'], $profile['call_permit']);
            $log['remark'] = $this->userId != $item['chat_user_id'] ? (new UserRemarkCache())->getRemark($this->userId, $item['chat_user_id']) : '';
            array_push($ret['list'], $log);
        }
        // log_user_result($userId, $ret);
        $this->packCommentTags($ret, $appId, $version);
        return $ret;
    }

    /**
     * 话单评价
     */
    function packCommentTags(&$ret = [], $appId = 1, $version = '')
    {
        if (!User::checkValidVersion($version, $appId, ['1.2.7'])) return;
        $channelIds = array_column($ret['list'], 'channel_id');
        $comments = CallComment::getCommentsByChannel($channelIds);
        foreach ($ret['list'] as &$item) {
            $item['comment_tags'] = $comments[$item['channel_id']] ?? [];
        }
        return;
    }
}
